package com.gyh.shiro;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gyh.config.Commons;
import com.gyh.service.UserService;



@Component
public class URLPermissionsFilter extends PermissionsAuthorizationFilter{

	private static final Logger logger = LoggerFactory.getLogger(URLPermissionsFilter.class);
	
	@Autowired
	private UserService userService;
	
	@Override
	public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws IOException {
		String curUrl =   getRequestUrl(request);
		Subject subject = SecurityUtils.getSubject();
		logger.info("curURl=="+curUrl);
		if (subject.getPrincipal() == null || StringUtils.endsWithAny(curUrl, ".js", ".css", ".html")
				|| StringUtils.endsWithAny(curUrl, ".jpg", ".png", ".gif", ".ico", ".jpeg")
				|| Commons.URLS.contains(curUrl)
				|| (subject.getPrincipal() != null && StringUtils.equals(curUrl, "/success.jsp") )) {
			return true;
		}
		Session session = subject.getSession();
		List<String> urls = userService.searchUrls((String)session.getAttribute("userName"));
		return urls.contains(curUrl);
	}
	
	private String getRequestUrl(ServletRequest request) {
		HttpServletRequest req = (HttpServletRequest) request;
		String queryString = req.getQueryString();

		queryString = StringUtils.isBlank(queryString) ? "" : "?" + queryString;
		return req.getRequestURI() + queryString;
	}
	
	
}
